from flask import Blueprint, request
from app.services.UserService import UserService
from app.services.AuthService import AuthService
from app.response import ResponseBuilder
from flask_login import login_user, login_required, logout_user


auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['POST'])
def login():
    """登录接口"""
    auth_service = AuthService()
    user_service = UserService()
    userName = request.json.get('userName')
    password = request.json.get('password')
    
    getUserByuserNameResult = user_service.getUserByUserName(username=userName)
    if getUserByuserNameResult:

        loginServiceResult = auth_service.loginService(userName = userName, password=password)
        if loginServiceResult:
            login_user(loginServiceResult)
            return ResponseBuilder.success(data=loginServiceResult.to_dict(), msg='登录成功')
        else:
            return ResponseBuilder.fail(msg='用户名或密码错误')
        
    else:
        return ResponseBuilder.fail(msg='用户不存在')

@auth_bp.route('/logout', methods=['GET'])
@login_required
def logout():
    """登出接口"""
    logout_user()
    return ResponseBuilder.success(msg='登出成功')